package org.sockettest.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

public class UserManager {
    private final List<Socket> sockets = new LinkedList<Socket>();

    public UserManager(){}
    public UserManager AddUser(Socket socket){
        synchronized (sockets){
            sockets.add(socket);
        }
        return this;
    }

    public UserManager DelUser(Socket socket){
        synchronized (sockets){
            sockets.remove(socket);
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return this;
    }

    public  UserManager DelAllUser(){
        synchronized (sockets){
            for(Socket socket: sockets){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return this;
    }

    public UserManager Say(Socket socket, String str){
        System.out.println(socket + " say");
        synchronized (sockets){
            for(Socket s : sockets){
                if(s == socket){
                    continue;
                }
                try {
                    PrintWriter pw = new PrintWriter(s.getOutputStream());
                    pw.printf("User %d: %s\n", s.getPort(), str);
//                    System.out.printf("User %d: %s\n", s.getPort(), str);
                    pw.flush();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return this;
    }
}
